package org.stvd.listener.workflow;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.event.ActivitiEntityEvent;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.pvm.PvmActivity;
import org.activiti.engine.task.IdentityLink;
import org.springframework.beans.factory.annotation.Autowired;
import org.stvd.common.Consts;
import org.stvd.common.DepAndUserHolder;
import org.stvd.common.security.SecurityUserHolder;
import org.stvd.common.workflow.WorkflowConsts;
import org.stvd.common.workflow.enums.WorkflowApproveStatusEnum;
import org.stvd.core.util.StringUtil;
import org.stvd.entities.admin.Users;
import org.stvd.entities.workflow.WfIndex;
import org.stvd.service.workflow.ProcessCoreService;
import org.stvd.service.workflow.WfIndexService;

/**
 * 创建了新任务。它位于 ENTITY_CREATE事件之后。当任务是由流程创建时， 这个事件会在TaskListener执行之前被执行。
 */
public class TaskCreatedListener implements EventHandler {

	@Autowired
	WfIndexService wfIndexService;
	@Autowired
	TaskService taskService;

	@Autowired
	private ProcessCoreService processCoreService;

	public void handle(ActivitiEvent event) {
		System.out.println("TaskCreateListener is " + event);
		ActivitiEntityEvent entityEvent = (ActivitiEntityEvent) event;
		TaskEntity taskEntity = (TaskEntity) entityEvent.getEntity();

		String candidate = "";
		String groupIds = "";
		for (Iterator<IdentityLink> iter = taskEntity.getCandidates().iterator(); iter.hasNext();) {
			IdentityLink identityLink = iter.next();
			if (!StringUtil.isEmpty(identityLink.getUserId())) {
				candidate += "," + identityLink.getUserId();
			}
			if (!StringUtil.isEmpty(identityLink.getGroupId())) {
				groupIds += "," + identityLink.getGroupId();
			}
		}
		if (!StringUtil.isEmpty(candidate)) {
			candidate = candidate.substring(1);
		}
		if (!StringUtil.isEmpty(groupIds)) {
			groupIds = groupIds.substring(1);
		}

		WfIndex wfIndex = wfIndexService.findByProcInstId(taskEntity.getProcessInstanceId());
		if (wfIndex != null) {
			if (StringUtil.isEmpty(wfIndex.getUserId())) {
				wfIndex.setDepId(taskEntity.getVariable(WorkflowConsts.INDEX_DEPARTMENT_ID).toString());
				wfIndex.setUserId(taskEntity.getVariable(WorkflowConsts.INDEX_USER_ID).toString());
			}
			wfIndex.setCandidate(candidate);
			wfIndex.setGroupId(groupIds);
			wfIndex.setTaskName(taskEntity.getName());
			wfIndex.setTaskId(taskEntity.getId());
//			if (StringUtil.isEmpty(taskEntity.getAssignee())) {
//				wfIndex.setAssignee("");
//				wfIndex.setStatus(WorkflowApproveStatusEnum.WaitingClaim.getValue());
//			} else {
			wfIndex.setStatus(WorkflowApproveStatusEnum.Pending.getValue());
//			}
			wfIndexService.update(wfIndex);
			PvmActivity targetActivity = processCoreService.findFirstActivity(entityEvent.getProcessDefinitionId());
			if (targetActivity.getId().equals(taskEntity.getExecution().getCurrentActivityId())) {
				try {
					Map<String, Object> variables = new HashMap<String, Object>();
					variables.put(WorkflowConsts.INDEX_USER_ID, wfIndex.getUserId());
					variables.put(WorkflowConsts.INDEX_USER_NAME, wfIndex.getUserId());
					processCoreService.transferAssignee(wfIndex.getTaskId(), SecurityUserHolder.getCurrentUserId(),
							variables);
					taskService.complete(wfIndex.getTaskId());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		if (StringUtil.isEmpty(wfIndex.getHistUsers()) && wfIndex.getUserId().equals(taskEntity.getAssignee())) {
			try {
				Map<String, Object> variables = taskEntity.getVariables();
				variables.put(WorkflowConsts.INDEX_SUGGESTION, "");
				variables.put(WorkflowConsts.INDEX_OPERATE_TYPE, WorkflowConsts.HANDLER_APPLY);
				processCoreService.passProcess(taskEntity.getId(), variables);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}